<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Chat Interface</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-50">
<div class="flex h-screen">
    <!-- Sidebar -->
    <div id="sidebar" class="w-64 bg-white border-r border-gray-200 flex flex-col">
        <div class="p-4">
            <button id="newChatBtn" class="w-full flex items-center gap-2 px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-lg transition-colors">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                    <path fill-rule="evenodd" d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z" clip-rule="evenodd" />
                </svg>
                新聊天
            </button>
        </div>
        <div id="chatList" class="flex-1 overflow-y-auto p-2 space-y-2"></div>
    </div>

    <!-- Main Content -->
    <div class="flex-1 flex flex-col">
        <!-- Top Bar -->
        <div class="bg-white border-b border-gray-200 p-4 flex items-center gap-4">
            <select id="modelSelect" class="px-4 py-2 border rounded-lg flex-1 max-w-xs">
                <option value="deepseek-r1:1.5b">deepseek-r1</option>
            </select>
            <select id="promptSelect" class="px-4 py-2 border rounded-lg flex-1 max-w-xs text-gray-400">
                <option>选择一个提示词</option>
            </select>
        </div>

        <!-- Chat Area -->
        <div id="chatArea" class="flex-1 overflow-y-auto p-4 space-y-4"></div>

        <!-- Input Area -->
        <div class="bg-white border-t border-gray-200 p-4">
            <div class="max-w-4xl mx-auto flex flex-col gap-4">
                <textarea id="messageInput" rows="3" class="w-full p-3 rounded-lg border border-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="输入一条消息..."></textarea>
                <div class="flex justify-between items-center">
                    <div class="flex items-center gap-2">
                        <button class="p-2 hover:bg-gray-100 rounded-lg">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                                <path fill-rule="evenodd" d="M4 5a2 2 0 00-2 2v8a2 2 0 002 2h12a2 2 0 002-2V7a2 2 0 00-2-2h-1.586a1 1 0 01-.707-.293l-1.121-1.121A2 2 0 0011.172 3H8.828a2 2 0 00-1.414.586L6.293 4.707A1 1 0 015.586 5H4zm6 9a3 3 0 100-6 3 3 0 000 6z" clip-rule="evenodd" />
                            </svg>
                        </button>
                        <button class="p-2 hover:bg-gray-100 rounded-lg">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                                <path fill-rule="evenodd" d="M7 4a3 3 0 016 0v4a3 3 0 11-6 0V4zm4 10.93A7.001 7.001 0 0017 8a1 1 0 10-2 0A5 5 0 015 8a1 1 0 00-2 0 7.001 7.001 0 006 6.93V17H6a1 1 0 100 2h8a1 1 0 100-2h-3v-2.07z" clip-rule="evenodd" />
                            </svg>
                        </button>
                    </div>
                    <button id="sendBtn" class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors">
                        发送
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
        // Chat management
        let chats = [];
        let currentChatId = null;

        // Initialize chat interface
        document.addEventListener('DOMContentLoaded', () => {
            // New chat button handler
            document.getElementById('newChatBtn').addEventListener('click', createNewChat);

            // Send message button handler
            document.getElementById('sendBtn').addEventListener('click', sendMessage);

            // Create initial chat
            createNewChat();
        });

        function createNewChat() {
            const chatId = Date.now().toString();
            const chat = {
                id: chatId,
                name: `新对话 ${chats.length + 1}`,
                messages: []
            };

            chats.push(chat);
            currentChatId = chatId;

            // Add to sidebar
            const chatList = document.getElementById('chatList');
            const chatElement = createChatListItem(chat);
            chatList.appendChild(chatElement);

            // Clear chat area
            document.getElementById('chatArea').innerHTML = '';
            document.getElementById('messageInput').value = '';
        }

        function createChatListItem(chat) {
            const div = document.createElement('div');
            div.className = 'flex items-center justify-between p-2 hover:bg-gray-100 rounded-lg cursor-pointer group';
            div.innerHTML = `
                <span class="flex-1">${chat.name}</span>
                <div class="hidden group-hover:flex items-center gap-2">
                    <button onclick="renameChatPrompt('${chat.id}')" class="p-1 hover:bg-gray-200 rounded">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                            <path d="M13.586 3.586a2 2 0 112.828 2.828l-.793.793-2.828-2.828.793-.793zM11.379 5.793L3 14.172V17h2.828l8.38-8.379-2.83-2.828z" />
                        </svg>
                    </button>
                    <button onclick="deleteChat('${chat.id}')" class="p-1 hover:bg-gray-200 rounded">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                            <path fill-rule="evenodd" d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z" clip-rule="evenodd" />
                        </svg>
                    </button>
                </div>
            `;

            div.addEventListener('click', (e) => {
                if (!e.target.closest('button')) {
                    selectChat(chat.id);
                }
            });

            return div;
        }

        function selectChat(chatId) {
            currentChatId = chatId;
            const chat = chats.find(c => c.id === chatId);

            // Update chat area
            const chatArea = document.getElementById('chatArea');
            chatArea.innerHTML = '';
            chat.messages.forEach(msg => {
                appendMessage(msg.role, msg.content);
            });
        }

        function renameChatPrompt(chatId) {
            const chat = chats.find(c => c.id === chatId);
            const newName = prompt('请输入新的对话名称:', chat.name);
            if (newName) {
                chat.name = newName;
                updateChatList();
            }
        }

        function deleteChat(chatId) {
            if (confirm('确定要删除这个对话吗？')) {
                chats = chats.filter(c => c.id !== chatId);
                updateChatList();
                if (currentChatId === chatId) {
                    if (chats.length > 0) {
                        selectChat(chats[0].id);
                    } else {
                        createNewChat();
                    }
                }
            }
        }

        function updateChatList() {
            const chatList = document.getElementById('chatList');
            chatList.innerHTML = '';
            chats.forEach(chat => {
                chatList.appendChild(createChatListItem(chat));
            });
        }

        function appendMessage(role, content) {
            const chatArea = document.getElementById('chatArea');
            const messageDiv = document.createElement('div');
            messageDiv.className = `flex ${role === 'user' ? 'justify-end' : 'justify-start'}`;

            const bubble = document.createElement('div');
            bubble.className = `max-w-[80%] p-3 rounded-lg ${
                role === 'user'
                    ? 'bg-blue-500 text-white'
                    : 'bg-gray-100 text-gray-800'
            }`;
            bubble.textContent = content;

            messageDiv.appendChild(bubble);
            chatArea.appendChild(messageDiv);
            chatArea.scrollTop = chatArea.scrollHeight;
        }

        async function sendMessage() {
            const input = document.getElementById('messageInput');
            const message = input.value.trim();
            if (!message) return;

            // Clear input
            input.value = '';

            // Add user message
            appendMessage('user', message);

            // Get current chat
            const chat = chats.find(c => c.id === currentChatId);
            chat.messages.push({ role: 'user', content: message });

            // Create API URL with parameters
            const model = document.getElementById('modelSelect').value;
            const apiUrl = `http://localhost:8090/api/v1/ollama/generate_stream?model=${encodeURIComponent(model)}&message=${encodeURIComponent(message)}`;

            try {
                // Create temporary div for assistant's response
                const assistantMessage = document.createElement('div');
                assistantMessage.className = 'flex justify-start';
                const bubble = document.createElement('div');
                bubble.className = 'max-w-[80%] p-3 rounded-lg bg-gray-100 text-gray-800';
                assistantMessage.appendChild(bubble);
                document.getElementById('chatArea').appendChild(assistantMessage);

                // Set up EventSource
                const eventSource = new EventSource(apiUrl);
                let fullResponse = '';

                eventSource.onmessage = (event) => {
                    try {
                        const data = JSON.parse(event.data);
                        const content = data.result.output.content;
                        const finishReason = data.result.metadata.finishReason;

                        if (content) {
                            fullResponse += content;
                            bubble.textContent = fullResponse;
                            document.getElementById('chatArea').scrollTop = document.getElementById('chatArea').scrollHeight;
                        }

                        if (finishReason === 'STOP') {
                            eventSource.close();
                            chat.messages.push({ role: 'assistant', content: fullResponse });
                        }
                    } catch (error) {
                        console.error('Error parsing message:', error);
                    }
                };

                eventSource.onerror = (error) => {
                    console.error('EventSource failed:', error);
                    eventSource.close();
                };
            } catch (error) {
                console.error('Error sending message:', error);
            }
        }
    </script>
</body>
</html>